import React, { useState, useEffect, useRef } from'react';
import { Form, Input, InputNumber, Upload, Button, Checkbox, TimePicker, Modal, message } from 'antd';
import { PlusOutlined, DeleteOutlined, ZoomInOutlined } from '@ant-design/icons';
import style from './index.module.less';
import { shopInfo, shopEdit } from '@/api/shop';
import { serverUrl } from '../../../src/utils/comment';

const { TextArea } = Input;

const Shop = () => {
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [formData, setFormData] = useState({
        id: '',
        name: '',
        bulletin: '',
        avatar: '',
        pics: '',
        minPrice: '',
        deliveryTime: '',
        description: '',
        score: '',
        sellCount: '',
        supports: [],
        date: []
    });

    useEffect(() => {
        fetchShopInfo();
    }, []);

    const fetchShopInfo = async () => {
       
            const res = await shopInfo();
            if (res.data) {
                setFormData(res.data);
                setFileList(
                    res.data.pics.map((item) => ({
                        uid: -item,
                        name: item,
                        status: 'done',
                        url: `${serverUrl}${item}`
                    }))
                );
                form.setFieldsValue({
                    id: res.data.id,
                    name: res.data.name,
                    bulletin: res.data.bulletin,
                    avatar: res.data.avatar,
                    minPrice: res.data.minPrice,
                    deliveryTime: res.data.deliveryTime,
                    description: res.data.description,
                    score: res.data.score,
                    sellCount: res.data.sellCount,
                    supports: res.data.supports,
                    date: res.data.date.map((time) => new Date(time)),
                    deliveryPrice: res.data.deliveryPrice // 新增配送费字段
                });
            } else {
                message.error('获取的店铺信息为空');
            }
        
    };

    const handleSave = async () => {
        try {
            const values = await form.validateFields();
            const newFormData = {
               ...values,
                date: values.date.map((time) => time.toISOString().slice(11, 19)),
                supports: JSON.stringify(values.supports),
                avatar: values.avatar.replace(serverUrl, ''),
                pics: fileList.map((file) => file.name)
            };
            const { code, msg } = await shopEdit(newFormData);
            if (code === 0) {
                message.success(msg);
                fetchShopInfo();
            } else {
                message.error(msg);
            }
        } catch (error) {
            message.error('表单验证失败');
        }
    };

    const handleAvatarSuccess = (response) => {
        form.setFieldsValue({ avatar: response.imgUrl });
        setFormData({
           ...formData,
            avatar: response.imgUrl
        });
    };

    const handleRemove = (file) => {
        const newFileList = fileList.filter((item) => item.uid!== file.uid);
        setFileList(newFileList);
    };

    const handlePreview = (file) => {
        setPreviewImage(file.url);
        setPreviewVisible(true);
    };

    const beforeUpload = (file) => {
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
            message.error('只能上传图片文件');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片大小不能超过 2MB');
        }
        return isImage && isLt2M;
    };

    return (
        <div className={style.main}>
            <div className={style.container}>
                <p className={style.title}>店铺管理</p>
                <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 14 }} layout="horizontal">
                    <Form.Item label="店铺名称" name="name">
                        <Input />
                    </Form.Item>
                    <Form.Item label="公告" name="bulletin">
                        <TextArea rows={5} />
                    </Form.Item>
                    <Form.Item label="店铺头像" name="avatar">
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className={style['avatar-uploader']}
                            showUploadList={false}
                            action={`${serverUrl}api/shop/upload`}
                            beforeUpload={beforeUpload}
                            onChange={({ fileList: newFileList }) => {
                                if (newFileList.length > 0) {
                                    form.setFieldsValue({ avatar: newFileList[0].response?.imgUrl });
                                }
                            }}
                            onSuccess={handleAvatarSuccess}
                            fileList={fileList.filter(file => file.uid === 'avatar')} // 确保没有无效的 value 属性
                        >
                            {form.getFieldValue('avatar')? (
                                <img src={`${serverUrl}${form.getFieldValue('avatar')}`} alt="avatar" className={style.avatar} />
                            ) : (
                                <PlusOutlined />
                            )}
                        </Upload>
                    </Form.Item>
                    <Form.Item label="店铺介绍图" name="pics">
                        <Upload
                            action={`${serverUrl}api/shop/upload`}
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onRemove={handleRemove}
                            beforeUpload={beforeUpload}
                            onChange={({ fileList: newFileList }) => setFileList(newFileList)}
                        >
                            <PlusOutlined />
                        </Upload>
                    </Form.Item>
                    <Form.Item label="起送价格" name="minPrice">
                        <InputNumber min={0} max={1000} />
                    </Form.Item>
                    <Form.Item label="送达时间" name="deliveryTime">
                        <InputNumber min={0} max={1000} />
                    </Form.Item>
                    <Form.Item label="配送费" name="deliveryPrice">
                        <InputNumber min={0} max={100} />
                    </Form.Item>
                    <Form.Item label="配送描述" name="description">
                        <Input />
                    </Form.Item>
                    <Form.Item label="店铺评分" name="score">
                        <InputNumber min={0} max={10} step={0.1} />
                    </Form.Item>
                    <Form.Item label="店铺销量" name="sellCount">
                        <InputNumber min={0} max={100000} />
                    </Form.Item>
                    <Form.Item label="店铺活动" name="supports">
                        <Checkbox.Group>
                            <Checkbox value="单人精彩套餐">单人精彩套餐</Checkbox>
                            <Checkbox value="VC无限橙果汁全场8折">VC无限橙果汁全场8折</Checkbox>
                            <Checkbox value="在线支付满28减5">在线支付满28减5</Checkbox>
                            <Checkbox value="特价饮品八折抢购">特价饮品八折抢购</Checkbox>
                            <Checkbox value="中秋特惠">中秋特惠</Checkbox>
                            <Checkbox value="国庆特价">国庆特价</Checkbox>
                            <Checkbox value="春节1折折扣">春节1折折扣</Checkbox>
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item label="营业时间" name="date">
                        <TimePicker.RangePicker format="HH:mm:ss" />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4, span: 14 }}>
                        <Button type="primary" onClick={handleSave}>
                            保存
                        </Button>
                    </Form.Item>
                </Form>
                <Modal
                    open={previewVisible} // 使用 open 替代 visible
                    title="图片预览"
                    footer={null}
                    onCancel={() => setPreviewVisible(false)}
                >
                    <img src={previewImage} alt="preview" style={{ width: '100%' }} />
                </Modal>
            </div>
        </div>
    );
};

export default Shop;    